import RPi.GPIO as GPIO
import time

# 定义引脚
LED_PIN_RED = 17
LED_PIN_GREEN = 18
LED_PIN_BLUE = 27
BUZZER_PIN = 22
VIBRATION_PIN = 23

# 初始化 GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN_RED, GPIO.OUT)
GPIO.setup(LED_PIN_GREEN, GPIO.OUT)
GPIO.setup(LED_PIN_BLUE, GPIO.OUT)
GPIO.setup(BUZZER_PIN, GPIO.OUT)
GPIO.setup(VIBRATION_PIN, GPIO.IN)

# 创建 PWM 实例
pwm_red = GPIO.PWM(LED_PIN_RED, 100)
pwm_green = GPIO.PWM(LED_PIN_GREEN, 100)
pwm_blue = GPIO.PWM(LED_PIN_BLUE, 100)
pwm_red.start(0)
pwm_green.start(0)
pwm_blue.start(0)


def read_vibration_intensity():
    """
    模拟读取震动强度
    """
    vibration_count = 0
    for _ in range(10):
        if GPIO.input(VIBRATION_PIN) == GPIO.HIGH:
            vibration_count += 1
        time.sleep(0.01)
    return vibration_count


try:
    while True:
        # 读取震动强度
        intensity = read_vibration_intensity()
        # 根据震动强度计算 LED 亮度
        brightness = min(intensity * 10, 100)

        # 设置三色 LED 亮度
        pwm_red.ChangeDutyCycle(brightness)
        pwm_green.ChangeDutyCycle(brightness)
        pwm_blue.ChangeDutyCycle(brightness)

        # 如果有震动，蜂鸣器发声
        if intensity > 0:
            GPIO.output(BUZZER_PIN, GPIO.HIGH)
        else:
            GPIO.output(BUZZER_PIN, GPIO.LOW)

        time.sleep(0.1)

except KeyboardInterrupt:
    print("程序被中断，清理 GPIO...")
finally:
    pwm_red.stop()
    pwm_green.stop()
    pwm_blue.stop()
    GPIO.cleanup()